package com.vader.juc.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author kaivader
 */

public class AtomicIntegerFiledUpdate {

    public static void main(String[] args) throws InterruptedException {
        BankCount bankCount = new BankCount();
        CountDownLatch countDownLatch = new CountDownLatch(1000);

        for (int i = 0; i < 1000; i++) {
            try {
                new Thread(() -> {
                    bankCount.transfer(bankCount);
                }, String.valueOf(i)).start();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }

        countDownLatch.await();

        System.out.println(bankCount.money);

    }


}


class BankCount {
    public String name = "ccc";
    public volatile int money;

    AtomicIntegerFieldUpdater updater = AtomicIntegerFieldUpdater.newUpdater(BankCount.class, "money");

    public void transfer(BankCount bankCount) {
        updater.incrementAndGet(bankCount);
    }
}